/*
 * Copyright 2016 Wealth Inc. All rights reserved.
 */
 package com.wealth.order.service.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import javax.transaction.Transactional;
import javax.xml.crypto.KeySelector.Purpose;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;

import com.wealth.cart.entity.Cart;
import com.wealth.cart.entity.CartItem;
import com.wealth.cart.enums.CartStatusEnum;
import com.wealth.cart.service.ICartItemService;
import com.wealth.cart.service.ICartService;
import com.wealth.commodity.entity.Goods;
import com.wealth.commodity.entity.Purrestrictions;
import com.wealth.commodity.repository.PurrestrictionsDao;
import com.wealth.commodity.service.IGoodsService;
import com.wealth.member.entity.Member;
import com.wealth.merchant.entity.Merchant;
import com.wealth.merchant.enums.MarketEnum;
import com.wealth.merchant.repository.MerchantDao;
import com.wealth.order.entity.Order;
import com.wealth.order.entity.OrderItem;
import com.wealth.order.entity.OrderPlat;
import com.wealth.order.enums.OrderStatusEnum;
import com.wealth.order.enums.PayStatusEnum;
import com.wealth.order.repository.OrderDao;
import com.wealth.order.repository.OrderItemDao;
import com.wealth.order.service.IOrderService;
import com.wealth.order.service.IVoucherRecordService;
import com.wealth.order.vo.OrderVOCenter;

import iaas.enums.StatusEnum;
import iaas.enums.YesOrNoEnum;
import iaas.persistence.DynamicSpecifications;
import iaas.persistence.SearchFilter;
import iaas.persistence.SearchFilter.Operator;
import iaas.service.impl.BaseServiceImpl;
import iaas.utils.Reflections;
import iaas.utils.ResultObject;
import iaas.web.JqGridRequest;

/**
 * @author chan
 * @version 1.0
 * @since 1.0
 */
 
@Component
public class OrderServiceImpl extends BaseServiceImpl<Order> implements IOrderService{

	@Autowired
	private OrderDao orderDao;
	@Autowired
	private OrderItemDao orderItemDao;
	@Autowired
	private MerchantDao merchantDao;
	@Autowired
	private IGoodsService goodsService;
	@Autowired
	private IVoucherRecordService recordService;
	@Autowired
	private ICartItemService cartItemService;
	@Autowired
	private ICartService cartService;
	@Autowired
	private PurrestrictionsDao purrestrictionsDao;

	/** 分页查询   商户订单  */
	@Override
	public Page<Order> getOrder(Long merchantid, JqGridRequest request,
			Class<Order> clz) throws Exception {
		//创建分页请求.
		int pageNumber = request.getPage();
		int pageSize = request.getRows();
		String sortType = StringUtils.isEmpty(request.getSidx())?"id":request.getSidx();
		String sortDirection = StringUtils.isEmpty(request.getSord())?"desc":request.getSord();
		Direction direction = sortDirection.equals("desc")?Direction.DESC:Direction.ASC;
		Sort sort = new Sort(direction, sortType);
		PageRequest pageRequest = new PageRequest(pageNumber - 1, pageSize, sort);

		//创建动态查询条件组合.
		Collection<SearchFilter> filters = SearchFilter.parse(request);
		//过滤商户订单
		if(Reflections.existsField("merchant", clz)){
			if(merchantid!=1L){
				filters.add(new SearchFilter("merchant.id", Operator.EQ, merchantid));
			}
		}
		//过滤:状态
		if(Reflections.existsField("status", clz)){
			filters.add(new SearchFilter("status", Operator.NE, StatusEnum.DELETE.getValue()));
		}
		Specification<Order> spec = DynamicSpecifications.bySearchFilter(filters, clz);
		return orderDao.findAll(spec, pageRequest);
	}
	
	/** 查询  银行订单下商户订单 */
	@Override
	public List<Order> findByOrderPlatId(Long orderPlatId) {
		return orderDao.findByOrderPlatId(orderPlatId);
	}
	
	
	/** ---------------- 微信端 ---------------- */
	
	/** 保存商户订单 */
	@Transactional
	@Override
	public ResultObject saveOrder(Order order) throws Exception {
		
		

		/* ------------ 业务逻辑 ------------ **/
		// 保存订单
		String orderno = String.valueOf(System.currentTimeMillis())+ RandomStringUtils.random(3, "1234567890");
		order.setOrderno(orderno);
		orderDao.save(order);
		
		// 保存订单明细
		for (OrderItem item : order.getOrderItemList()) {
			item.setOrder(order);
			orderItemDao.save(item);
		}
		
		
		
		return new ResultObject("000", "保存商户订单成功","");
	}
	
	/** 支付商户订单 */
	public void payOrder(Order order) throws Exception{
		// 编辑订单明细
		for (OrderItem item : order.getOrderItemList()) {
			//商品启用库存，减少商品库存
			//if(item.getGoods().getIsInventory()==YesOrNoEnum.YES.getValue()){
			//   goodsService.decreaseRemain(item.getGoods().getId(),item.getAmount());
			//}
			// 增加销量
			goodsService.increaseSales(item.getGoods().getId(),item.getAmount());
			//商品是否限购
			if(item.getGoods().getIsPurRestrictions()==YesOrNoEnum.YES.getValue()){
				Purrestrictions purrestrictions=new Purrestrictions();
				purrestrictions.setMember(new Member(order.getMember().getId()));
				purrestrictions.setGoods(new Goods(item.getGoods().getId()));
				purrestrictions.setAmount(item.getAmount());
				purrestrictions.setCreatetime(new Date());
				purrestrictionsDao.save(purrestrictions);
			}
		}

		// 编辑订单
		order.setPaystatus(PayStatusEnum.YES.getValue());
		order.setStatus(OrderStatusEnum.PAY.getValue());
		order.setPayTime(new Date());
		orderDao.save(order);
		
		//如果购买的是虚拟商品或者自提商品，生成代金券
		Merchant merchant = merchantDao.findOne(order.getMerchant().getId());
		if(merchant.getMarket().getId()==MarketEnum.LIFE.getValue()){
			recordService.generateVoucherRecord(order);
		}
		
	}
	
	
	/** 
	 * 加载商户订单
	 * @param marketid  		会员
	 * @param status 			状态
	 * @param index				id从index开始
	 * @param offset 				查询offset条数据
	 */
	@Override
	public List<OrderVOCenter> ajaxOrder(Long memberid,  Integer status, Integer index, Integer offset) throws Exception {
		
		/** ---- 分页查询 ---*/
		//创建分页请求.
		Sort sort = new Sort(Direction.DESC,"id");
		PageRequest pageRequest = new PageRequest(0, offset, sort);
		
		//创建动态查询条件组合.
		Collection<SearchFilter> filters = new ArrayList<SearchFilter>();
		//过滤:会员
		filters.add(new SearchFilter("member.id", Operator.EQ, memberid));
		
		//查询未评论，传入参数7
		if(status==OrderStatusEnum.NOTEVALUATE.getValue()){
			//过滤:支付状态
			filters.add(new SearchFilter("paystatus", Operator.EQ, YesOrNoEnum.YES.getValue()));
			//过滤:签收状态
			filters.add(new SearchFilter("signstatus", Operator.EQ, YesOrNoEnum.YES.getValue()));
			
			List<org.springframework.data.domain.Sort.Order> orders = new ArrayList<Sort.Order>();
			orders.add(new org.springframework.data.domain.Sort.Order(Direction.DESC, "createTime"));
			orders.add(new org.springframework.data.domain.Sort.Order(Direction.ASC, "evaluatestatus"));
			Sort mysort =new Sort(orders);
			pageRequest = new PageRequest(0, offset, mysort);
			
		//查询未发货 （已支付，未发货），传入参数3	
		}else if(status==OrderStatusEnum.PAY.getValue()){//
			//过滤:发货状态
			filters.add(new SearchFilter("deliverstatus", Operator.EQ, YesOrNoEnum.NO.getValue()));
			//过滤:支付状态
			filters.add(new SearchFilter("paystatus", Operator.EQ, YesOrNoEnum.YES.getValue()));
		//查询未签收(已发货，已支付，未签收)，传入参数4
		}else if(status==OrderStatusEnum.SEND.getValue()){//
			//过滤:签收状态
			filters.add(new SearchFilter("deliverstatus", Operator.EQ, YesOrNoEnum.YES.getValue()));
			//过滤:支付状态
			filters.add(new SearchFilter("paystatus", Operator.EQ, YesOrNoEnum.YES.getValue()));
			//过滤:签收状态
			filters.add(new SearchFilter("signstatus", Operator.EQ, YesOrNoEnum.NO.getValue()));
		}else{
			//过滤:状态
			filters.add(new SearchFilter("status", Operator.EQ, status));
			//过滤:支付状态
			filters.add(new SearchFilter("paystatus", Operator.EQ, PayStatusEnum.NO.getValue()));
		}
		//过滤：id<index
		if(index!=-1){
			filters.add(new SearchFilter("id", Operator.LT, index));
		}
		Specification<Order> spec = DynamicSpecifications.bySearchFilter(filters, Order.class);
		Page<Order> page  = orderDao.findAll(spec, pageRequest);
		List<Order> orderList =page.getContent();
		List<OrderVOCenter> voList =new ArrayList<OrderVOCenter>();
		if(orderList.size()>0){
			for (Order order : orderList) {
				OrderVOCenter vo =new OrderVOCenter();
				vo.setOrder(order);
				vo.setOrderItemList(order.getOrderItemList());
				voList.add(vo);
			}
		}
		
		return voList;
	}
	
	/** 商户月消费人数 */
	public Integer avgConsumeNumberByMerchantId(Long merchantid,Date start,Date end) throws Exception{
		Integer temp = orderDao.avgConsumeNumberByMerchantId(merchantid, start, end);
		if(temp==null){
			temp = 0;
		}
		return temp;
	}
	
	/** 商户平均消费 */
	public Integer avgTotalByMerchantId(Long merchantid) throws Exception{
		Integer temp = orderDao.avgTotalByMerchantId(merchantid);
		if(temp==null){
			temp = 0;
		}
		return temp;
	}

	/** 商户消费记录 */
	@Override
	public List<OrderVOCenter> ajaxConsumption(Long memberid, Integer status,
			Integer index, Integer offset) throws Exception {
		
		/** ---- 分页查询 ---*/
		//创建分页请求.
		Sort sort = new Sort(Direction.DESC,"id");
		PageRequest pageRequest = new PageRequest(0, offset, sort);
		//创建动态查询条件组合.
		Collection<SearchFilter> filters = new ArrayList<SearchFilter>();
		//过滤:会员
		filters.add(new SearchFilter("member.id", Operator.EQ, memberid));
	
		//过滤:支付状态
		filters.add(new SearchFilter("paystatus", Operator.EQ, YesOrNoEnum.YES.getValue()));
		
		//过滤：id<index
		if(index!=-1){
			filters.add(new SearchFilter("id", Operator.LT, index));
		}
		Specification<Order> spec = DynamicSpecifications.bySearchFilter(filters, Order.class);
		Page<Order> page  = 	orderDao.findAll(spec, pageRequest);
		List<OrderVOCenter> voList = new ArrayList<OrderVOCenter>();
		List<Order> orderList = page.getContent();
		if(orderList.size()>0){
			for (Order order : orderList) {
				OrderVOCenter vo = new OrderVOCenter();
				vo.setOrder(order);
				vo.setOrderItemList(order.getOrderItemList());
				voList.add(vo);
			}
		}
		return voList;
	}
	/** 商户消费记录 */
	@Override
	public ResultObject ajaxConsumptionPage(Long memberid, Integer status,
			Integer pageNumber, Integer pageSize) throws Exception {
		
		/** ---- 分页查询 ---*/
		//创建分页请求.
		Sort sort = new Sort(Direction.DESC,"id");
		PageRequest pageRequest = new PageRequest(pageNumber-1, pageSize, sort);
		//创建动态查询条件组合.
		Collection<SearchFilter> filters = new ArrayList<SearchFilter>();
		//过滤:会员
		filters.add(new SearchFilter("member.id", Operator.EQ, memberid));
	
		//过滤:支付状态
		filters.add(new SearchFilter("paystatus", Operator.EQ, YesOrNoEnum.YES.getValue()));
		Specification<Order> spec = DynamicSpecifications.bySearchFilter(filters, Order.class);
		
		Page<Order> page  = 	orderDao.findAll(spec, pageRequest);
		Long count= page.getTotalElements();
		List<OrderVOCenter> voList = new ArrayList<OrderVOCenter>();
		List<Order> orderList = page.getContent();
		if(orderList.size()>0){
			for (Order order : orderList) {
				OrderVOCenter vo = new OrderVOCenter();
				vo.setOrder(order);
				vo.setOrderItemList(order.getOrderItemList());
				voList.add(vo);
			}
		}
		return new ResultObject("000", String.valueOf(count), voList);
	}
	
	/** 发货商户订单 */
	public void send(Order order) throws Exception{
		order.setDeliverstatus(YesOrNoEnum.YES.getValue());
		order.setStatus(OrderStatusEnum.SEND.getValue());
		order.setDeliverTime(new Date());
		orderDao.save(order);
	}

	/** 签收商户订单 */
	@Override
	public ResultObject sign(Order order) throws Exception {
		if(order.getSignstatus()==YesOrNoEnum.YES.getValue()){
			return new ResultObject("500", "商品已签收过", "");
		}
		order.setSignstatus(YesOrNoEnum.YES.getValue());
		order.setStatus(OrderStatusEnum.SIGN.getValue());
		orderDao.save(order);
		return new ResultObject("000", "商品签收成功", "");
	}
	
	/** 统计数目商户 未付款 1/未发货 2/未签收 3/未评论 7 */
	public Integer countOrder(Long memberid, Integer status) throws Exception{
		
		//创建动态查询条件组合.
		Collection<SearchFilter> filters = new ArrayList<SearchFilter>();
		//过滤:会员
		filters.add(new SearchFilter("member.id", Operator.EQ, memberid));
		
		//查询未评论，传入参数7
		if(status==OrderStatusEnum.NOTEVALUATE.getValue()){
			//过滤:支付状态
			filters.add(new SearchFilter("paystatus", Operator.EQ, YesOrNoEnum.YES.getValue()));
			//过滤:签收状态
			filters.add(new SearchFilter("signstatus", Operator.EQ, YesOrNoEnum.YES.getValue()));
			
		//查询未发货 ，传入参数3	
		}else if(status==OrderStatusEnum.PAY.getValue()){//
			//过滤:发货状态
			filters.add(new SearchFilter("deliverstatus", Operator.EQ, YesOrNoEnum.NO.getValue()));
			//过滤:支付状态
			filters.add(new SearchFilter("paystatus", Operator.EQ, YesOrNoEnum.YES.getValue()));
			
		//查询未签收，传入参数4
		}else if(status==OrderStatusEnum.SEND.getValue()){//
			//过滤:签收状态
			filters.add(new SearchFilter("deliverstatus", Operator.EQ, YesOrNoEnum.YES.getValue()));
			//过滤:支付状态
			filters.add(new SearchFilter("paystatus", Operator.EQ, YesOrNoEnum.YES.getValue()));
			//过滤:签收状态
			filters.add(new SearchFilter("signstatus", Operator.EQ, YesOrNoEnum.NO.getValue()));
		}else{
			//过滤:状态
			filters.add(new SearchFilter("status", Operator.EQ, status));
			//过滤:支付状态
			filters.add(new SearchFilter("paystatus", Operator.EQ, PayStatusEnum.NO.getValue()));
		}
		
		Specification<Order> spec = DynamicSpecifications.bySearchFilter(filters, Order.class);
		List<Order> list  = orderDao.findAll(spec);
		return list.size();
	}
	
	
	/** 统计订单数 已付款  */
	public Integer countPayStatusOrder(Long memberid)  throws Exception{
		//创建动态查询条件组合.
		Collection<SearchFilter> filters = new ArrayList<SearchFilter>();
		//过滤:会员
		filters.add(new SearchFilter("member.id", Operator.EQ, memberid));
		//过滤:支付状态
		filters.add(new SearchFilter("paystatus", Operator.EQ, YesOrNoEnum.YES.getValue()));
		Specification<Order> spec = DynamicSpecifications.bySearchFilter(filters, Order.class);
		List<Order> list  = orderDao.findAll(spec);
		return list.size();
	}

	@Override
	public ResultObject ajaxOrderPage(Long memberid, Integer status, Integer pageNumber, Integer pageSize)
			throws Exception {

		/** ---- 分页查询 ---*/
		//创建分页请求.
		Sort sort = new Sort(Direction.DESC,"id");
		PageRequest pageRequest = new PageRequest(pageNumber-1, pageSize, sort);
		
		//创建动态查询条件组合.
		Collection<SearchFilter> filters = new ArrayList<SearchFilter>();
		//过滤:会员
		filters.add(new SearchFilter("member.id", Operator.EQ, memberid));
		
		//查询未评论，传入参数7
		if(status==OrderStatusEnum.NOTEVALUATE.getValue()){
			//过滤:支付状态
			filters.add(new SearchFilter("paystatus", Operator.EQ, YesOrNoEnum.YES.getValue()));
			//过滤:签收状态
			filters.add(new SearchFilter("signstatus", Operator.EQ, YesOrNoEnum.YES.getValue()));
			
			List<org.springframework.data.domain.Sort.Order> orders = new ArrayList<Sort.Order>();
			orders.add(new org.springframework.data.domain.Sort.Order(Direction.DESC, "createTime"));
			orders.add(new org.springframework.data.domain.Sort.Order(Direction.ASC, "evaluatestatus"));
			Sort mysort =new Sort(orders);
			pageRequest = new PageRequest(0, pageSize, mysort);
			
		//查询未发货 （已支付，未发货），传入参数3	
		}else if(status==OrderStatusEnum.PAY.getValue()){//
			
			filters.add(new SearchFilter("status", Operator.EQ,OrderStatusEnum.PAY.getValue()));
			//过滤:发货状态
			filters.add(new SearchFilter("deliverstatus", Operator.EQ, YesOrNoEnum.NO.getValue()));
			//过滤:支付状态
			filters.add(new SearchFilter("paystatus", Operator.EQ, YesOrNoEnum.YES.getValue()));
		//查询未签收(已发货，已支付，未签收)，传入参数4
		}else if(status==OrderStatusEnum.SEND.getValue()){//
			//过滤:签收状态
			filters.add(new SearchFilter("deliverstatus", Operator.EQ, YesOrNoEnum.YES.getValue()));
			//过滤:支付状态
			filters.add(new SearchFilter("paystatus", Operator.EQ, YesOrNoEnum.YES.getValue()));
			//过滤:签收状态
			filters.add(new SearchFilter("signstatus", Operator.EQ, YesOrNoEnum.NO.getValue()));
		/**查询所有的订单*/
		}else if(status==OrderStatusEnum.NOTPAY.getValue()){
			//过滤:状态
			filters.add(new SearchFilter("status", Operator.EQ, status));
			//过滤:支付状态
			filters.add(new SearchFilter("paystatus", Operator.EQ, PayStatusEnum.NO.getValue()));
		}
		else{
			//过滤:状态
			filters.add(new SearchFilter("status", Operator.NE, status));
		}
		Specification<Order> spec = DynamicSpecifications.bySearchFilter(filters, Order.class);
		Page<Order> page  = orderDao.findAll(spec, pageRequest);
		Long count = page.getTotalElements();
		List<OrderVOCenter> voList = new ArrayList<OrderVOCenter>();
		List<Order> orderList = page.getContent();
		if(orderList.size()>0){
			for (Order order : orderList) {
				OrderVOCenter vo = new OrderVOCenter();
				vo.setOrder(order);
				vo.setOrderItemList(order.getOrderItemList());
				voList.add(vo);
			}
			return new ResultObject("000", String.valueOf(count), voList);
		}else{
			return new ResultObject("111", null,null);
		}
	}

	
	
	
	
}
